﻿using Microsoft.Win32;
using OdooRpcClient.Model.Base;
using PortaCapena.OdooJsonRpcClient;
using PortaCapena.OdooJsonRpcClient.Consts;
using PortaCapena.OdooJsonRpcClient.Models;
using Sunny.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using System.Xml;
using WebAssistant.BusinessLogic;
using WebAssistant.BusinessLogic.Model;
using WebAssistant.Common;

namespace Assistant.Tools
{
    public partial class FormReportList : UITitlePage
    {
        
        int pageSize = 40;
        int totalCount = 0;
        List<Reports> ReportData = new List<Reports>();
        string ReportFolderPath = AppDomain.CurrentDomain.BaseDirectory + @"\Report\Rdl\";

        static OdooConfig config = new OdooConfig(
            apiUrl: "",
            dbName: "",
            userName: "",
            password: ""
            );
        static OdooClient odooClient = new OdooClient(config);

        public FormReportList()
        {
            InitializeComponent();
            InitializeOdoo();
            InitializeControls();
        }

        private void InitializeOdoo()
        {
            string[] ConfigKeyList = new string[] {
                "odoo.server.url", "odoo.server.database", "odoo.server.user", "odoo.key", "odoo.server.password"
            };
            foreach (string configkey in ConfigKeyList)
            {
                if (!DataAccess.CheckSettingExists(configkey))
                {
                    ShowWarningDialog("Odoo服务器配置错误！请设置。");
                    return;
                }
            }
            config = new OdooConfig(
                apiUrl: DataAccess.GetSettingByKey("odoo.server.url"),
                dbName: DataAccess.GetSettingByKey("odoo.server.database"),
                userName: DataAccess.GetSettingByKey("odoo.server.user"),
                password: SecurityHelper.DecryptString(DataAccess.GetSettingByKey("odoo.server.password"), DataAccess.GetSettingByKey("odoo.key"))
                );
            odooClient = new OdooClient(config);
        }

        #region dataGridView
        private void InitializeControls()
        {
            dgvReports.AutoGenerateColumns = false;//禁用自动生成列
            dgvReports.ColumnHeadersDefaultCellStyle.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleCenter;

            //AllCells 调整列宽，以适合该列中的所有单元格的内容，包括标题单元格。
            //Fill 调整列宽，使所有列的宽度正好填充控件的显示区域，只需要水平滚动保证列宽在DataGridViewColumn.MinimumWidth属性值以上。相对列宽由相对DataGridViewColumn.FillWeight属性值决定。
            //dgvReports.Columns[10].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            DataGridViewTextBoxColumn ReportNameColumn = new DataGridViewTextBoxColumn();
            ReportNameColumn.Width = 380;
            ReportNameColumn.HeaderText = "报表名称";
            ReportNameColumn.DataPropertyName = "ReportName";
            dgvReports.Columns.Add(ReportNameColumn);

            DataGridViewTextBoxColumn DisplayNameColumn = new DataGridViewTextBoxColumn();
            DisplayNameColumn.Width = 250;
            DisplayNameColumn.HeaderText = "显示名称";
            DisplayNameColumn.DataPropertyName = "Name";
            dgvReports.Columns.Add(DisplayNameColumn);

            DataGridViewTextBoxColumn ModelColumn = new DataGridViewTextBoxColumn();
            ModelColumn.Width = 300;
            ModelColumn.HeaderText = "模型";
            ModelColumn.DataPropertyName = "Model";
            dgvReports.Columns.Add(ModelColumn);

            DataGridViewCheckBoxColumn UseAssistantColumn = new DataGridViewCheckBoxColumn();
            UseAssistantColumn.HeaderText = "使用助手";
            UseAssistantColumn.DataPropertyName = "UseAssistant";
            dgvReports.Columns.Add(UseAssistantColumn);

            DataGridViewButtonColumn JsonEditButtonColumn = new DataGridViewButtonColumn();
            JsonEditButtonColumn.HeaderText = "数据源";//添加按钮列的列名称
            JsonEditButtonColumn.Name = "JsonEdit";//添加按钮的名字
            JsonEditButtonColumn.DefaultCellStyle.NullValue = "编辑";//添加按钮显示的名字
            dgvReports.Columns.Add(JsonEditButtonColumn);

            DataGridViewButtonColumn RdlEditButtonColumn = new DataGridViewButtonColumn();
            RdlEditButtonColumn.HeaderText = "报表";//添加按钮列的列名称
            RdlEditButtonColumn.Name = "RdlEdit";//添加按钮的名字
            RdlEditButtonColumn.DefaultCellStyle.NullValue = "编辑";//添加按钮显示的名字
            dgvReports.Columns.Add(RdlEditButtonColumn);

            DataGridViewButtonColumn UploadButtonColumn = new DataGridViewButtonColumn();
            UploadButtonColumn.HeaderText = "上传报表";//添加按钮列的列名称
            UploadButtonColumn.Name = "Upload";//添加按钮的名字
            UploadButtonColumn.DefaultCellStyle.NullValue = "上传";//添加按钮显示的名字
            dgvReports.Columns.Add(UploadButtonColumn);

            dgvReports.ReadOnly = true;

            BindingData();
        }

        private void dgvReports_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Color color = dgvReports.RowHeadersDefaultCellStyle.ForeColor;
            if (dgvReports.Rows[e.RowIndex].Selected)
                color = dgvReports.RowHeadersDefaultCellStyle.SelectionForeColor;
            else
                color = dgvReports.RowHeadersDefaultCellStyle.ForeColor;
            //绘制行号
            using (SolidBrush b = new SolidBrush(color))
            {
                e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 6);
            }
        }

        private void BindingData()
        {
            int pageIndex = 1;
            var pageData = DataAccess.GetReportPageData(pageIndex, pageSize,totalCount);
           
            ReportData = pageData.Item1;
            totalCount = pageData.Item2;

            //设置数据源
            dgvReports.DataSource = ReportData;

            //设置分页控件总数
            paginationReports.TotalCount = totalCount;

            //设置分页控件每页数量
            paginationReports.PageSize = pageSize;
        }

        private void paginationReports_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            var pageData = DataAccess.GetReportPageData(pageIndex, pageSize, totalCount);
            ReportData = pageData.Item1;
            totalCount = pageData.Item2;
            dgvReports.DataSource = ReportData;
        }
        private void DgvReports_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            string ReportName = dgvReports.Rows[e.RowIndex].Cells[0].Value.ToString();
            if (e.ColumnIndex == dgvReports.Columns["JsonEdit"].Index)
            {
                FormJsonEditor formJsonEditor = new FormJsonEditor(ReportName);
                formJsonEditor.Show();
            }
            if (e.ColumnIndex == dgvReports.Columns["RdlEdit"].Index)
            {                
                string ReportFileName = ReportName + ".rdl";
 
                //创建报表
                if (!Directory.Exists(ReportFolderPath))
                {
                    //报表路径不存在，创建路径
                    Directory.CreateDirectory(ReportFolderPath);  
                }
                
                string ReportFile = ReportFolderPath + ReportFileName;
                if (!File.Exists(ReportFile))
                {
                    //报表文件不存在，创建报表文件
                    Reports report = DataAccess.GetReportByReportName(ReportName);
                    if (report.ReportTemplate != "")
                    {
                        //报表模板不为空时，创建该文件
                        XmlDocument xdoc = new XmlDocument();
                        xdoc.LoadXml(report.ReportTemplate);
                        xdoc.Save(ReportFile);
                    }
                    else
                    {
                        ShowErrorDialog("报表模板为空，无法生成报表! \n请联系管理员生成报表模板");
                    }
                }                

                if (File.Exists(ReportFile) && CheckPowerBIReportBuilder())
                {
                    //存在报表文件 和 已安装“Power BI Report Builder”
                    FileHelper.OpenFile(ReportFile);
                }
                else
                {
                    // 未安装“Power BI Report Builder”
                    string downloadUrl = "https://www.microsoft.com/zh-CN/download/confirmation.aspx?id=58158";
                    FormDownloadTip formDownloadTip = new FormDownloadTip(downloadUrl);
                    formDownloadTip.LabelTip.Text = "Power BI Report Builder 尚未安装";
                    formDownloadTip.ShowDialog();
                }

                //ShowErrorDialog("无法生成报表! \n" + "请联系开发者");

            }
            if (e.ColumnIndex == dgvReports.Columns["Upload"].Index)
            {
                ShowInfoDialog("上传 " + dgvReports.Rows[e.RowIndex].Cells[0].Value.ToString());
            }
        }
        #endregion


        #region 报表文件

        /// <summary>
        /// 检测 Power BI Report Builder 是否安装
        /// </summary>
        /// <returns>true: 有安裝, false:沒有安裝</returns>
        public static bool CheckPowerBIReportBuilder()
        {
            string displayName;

            string registryKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
            RegistryKey key = Registry.LocalMachine.OpenSubKey(registryKey);
            if (key != null)
            {
                foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
                {
                    displayName = subkey.GetValue("DisplayName") as string;
                    if (displayName != null && displayName.Contains("Power BI Report Builder"))
                    {
                        return true;
                    }
                }
                key.Close();
            }

            registryKey = @"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
            key = Registry.LocalMachine.OpenSubKey(registryKey);
            if (key != null)
            {
                foreach (RegistryKey subkey in key.GetSubKeyNames().Select(keyName => key.OpenSubKey(keyName)))
                {
                    displayName = subkey.GetValue("DisplayName") as string;
                    if (displayName != null && displayName.Contains("Power BI Report Builder"))
                    {
                        return true;
                    }
                }
                key.Close();
            }
            return false;
        }



        #endregion


        private async void brnUpdate_Click(object sender, EventArgs e)
        {
            var versionResult = await odooClient.GetVersionAsync();
            var loginResult = await odooClient.LoginAsync();
            if (loginResult.Failed)
            {
                ShowInfoDialog("登陆验证失败，请检查配置是否正确");
            }
            else if (loginResult.Succeed)
            {
                var reportRepository = new OdooRepository<IrActionsReportOdooModel>(config);
                reportRepository.Config.Context.Language = "zh_CN";
                reportRepository.Config.Context.Timezone = "AsiaChongqing";

                var reports = await reportRepository.Query()
                    .Where(x => x.UseAssistant, OdooOperator.EqualsTo, true)
                    .Select(x => new
                    {
                        x.Name,
                        x.Id,
                        x.Model,
                        x.ReportName,
                        x.UseAssistant,
                        x.AssistantRdlTemplate,
                        x.AssistantDataTemplate
                    })
                    .ToListAsync();

                if (reports.Succeed)
                {
                    List<Reports> reportList = new List<Reports>();

                    foreach (var report in reports.Value)
                    {                        
                        Reports rp = new Reports
                        {
                            Name = report.Name,
                            ReportId = Convert.ToInt32(report.Id),
                            ReportName = report.ReportName,
                            Model = report.Model,
                            ReportTemplate = report.AssistantRdlTemplate,
                            DataTemplate = report.AssistantDataTemplate,
                            UseAssistant = report.UseAssistant
                        };
                        reportList.Add(rp);
                    }
                    try
                    {
                        var result = DataAccess.BatchUpdateInsertReport(reportList);
                        ShowInfoNotifier(result.ToString() + "条报表记录同步成功！");                        
                    }
                    catch (Exception ex)
                    {
                        ShowErrorNotifier("报表记录失败:" + ex.ToString());
                    }
                    finally
                    {
                        BindingData();
                    }
                }
                else
                {
                    ShowInfoDialog("", reports.Error.ToString());
                }
            }

        }
    }

}
